﻿using System;
using System.Diagnostics;
using System.Xml;
using HamcoWcs.Tools.Tibco.Entities;

namespace HamcoWcs.Tools.Tibco.MesMsgService
{
    public class MesMsgParser_WcsWaitSend : IMesMsgParser
    {

        public EnumMesMsgStatus Status => EnumMesMsgStatus.WcsWaitSend;

        public void HandleEvent(MesMsgQueue message, Context context)
        {
            try
            {
                //try
                //{
                //    LogAll(message.Content, context);

                //}
                //catch (Exception)
                //{

                //}


                context.TibcoTool.Send(message.Content, context.SendSubject);
                if (message.RequestType == EnumMesRequestType.Report)
                {
                    message.Status = EnumMesMsgStatus.Completed;
                }
                else if (message.RequestType == EnumMesRequestType.Request)
                {
                    message.Status = EnumMesMsgStatus.WcsWaitRecv;
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                message.Status = EnumMesMsgStatus.Error;
            }
        }


        private void LogAll(string msg, Context context)
        {

            var messageName = XmlHelper.GetMessageName(msg);
            var timeStamp = XmlHelper.GetTransactionId(msg);
            var mesMsgQueue = new MesMsgQueueBak()
            {
                Id = 0,
                Sender = EnumMesMsgSender.WCS,
                Content = msg,
                EventName = messageName,
                Status = EnumMesMsgStatus.WcsWaitSend,
                Return = "",
                BusinessType = "",
                RequestType = EnumMesRequestType.Request,
                CreatedTime = DateTime.Now,
                LastUpdateTime = DateTime.Now,
                TransactionId = timeStamp
            };

            int count = context.Client.Insertable(mesMsgQueue).ExecuteCommand();
            if (count < 1)
            {
                var systemlog = new SystemErrorLog($"TibcoExchange Server:[ERROR]{timeStamp},{messageName}");
                context.Client.Insertable(systemlog).ExecuteCommand();
            }
        }
    }
}
